package com.ysd.crm.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ysd.crm.entity.Users;
import com.ysd.crm.mapper.UsersMapper;
import com.ysd.crm.service.LoginService;
import com.ysd.crm.utils.DateUtils;
import com.ysd.crm.utils.MD5Util;
import com.ysd.crm.utils.Result;
import com.ysd.crm.utils.StringUtil;

@Service
public class LoginServiceImpl implements LoginService {

	@Autowired
	private UsersMapper UM;

	@Override
	public Result login(Users u) {
		if (u == null) {
			// 登录没有传参数
			return Result.toClient(false, "违规操作");
		}
		if (StringUtil.isNull(u.getLoginName()) || StringUtil.isNull(u.getPassword())) {
			// 用户名或密码未填写
			return Result.toClient(false, "账号或密码错误");
		}
		Users user = UM.getUserByLoginName(u);// 查询用户信息
		if (user.getIsLockout().equals("是")) {
			//账号已锁定
			return Result.toClient(false, "账号已被锁定!<br/>锁定时间【"
					+ DateUtils.formatDateTimeByDate(DateUtils.StrToDate2(user.getLockTime(),null)) + "】<br/>请联系管理员解锁后登录");
		}
		if (!MD5Util.getMD5(u.getPassword()).equals(user.getPassword())) {
			// 密码错误 密码错误次数+1
			boolean lock = user.getPsdWrongTime()+1>4;
			UM.updateUserLoginInfo(new Users(user.getId(), null, null, lock?"是":null, null, user.getPsdWrongTime()+1, lock?DateUtils.formatDateTime(new Date(), "yyyy-MM-dd HH:mm:ss"):null, null, null, null));
			return Result.toClient(false, "密码错误"+(user.getPsdWrongTime()+1)+"次<br/>错误5次将锁定账号<br/>请谨慎操作");
		}
		Users up = new Users();
		up.setId(user.getId());
		up.setLastLoginTime(new Date());
		up.setPsdWrongTime(0);
		UM.updateUserLoginInfo(up);
		
		return Result.toClient(true, "登录成功~", Result.toJson(new Users(user.getId(), user.getLoginName())));
	}

}
